#!/bin/bash

#------------------------------------------------------------------------------
# Generates a directory with user specified template files.
#
# TODO:
#
# Notes:
# 	- Don't use the nounset option since it causes annoyances when handling
# 	  errors.
# Dependencies:
# 	- getopt
#------------------------------------------------------------------------------

set -e -o pipefail

die() {
	echo "skel: ${@}" && exit 1;
}

usage() {
	cat <<-USAGE_END
		Usage: skel -t [TEMPLATE] [OPTIONS] [PROJECTNAME]
		Generates a directory containing template files. By
		default, searches ~/.templates for template files. 

		Change the default searched directory either by using the -d option or
		by defining TEMPLATE_SEARCH_PATH. If both are specified, -d takes
		precedence.
		
		-t, --template [template]	The template to use
		-r, --replace [world]	Replace default values in template with word
		-d, --template-directory	[path] Path to where the template files are located
		-h, --help	Prints this message
	USAGE_END
	exit ${1}
}

if [[ $(getopt -T ; echo $?) != 4 ]] ; then
	die "$(cat <<-GETOPT_ERR_MSG_END
		Your getopt is not the enhanced version. Please install a more recent version
		version of getopt.
	GETOPT_ERR_MSG_END
	)"
fi

declare template word genpath="${PWD}" template_path="${HOME}/.templates"

short_opts='ht:r:d:'
long_opts='help,template:,replace:,template-directory:'
parsed=$(getopt --options ${short_opts} --longoptions ${long_opts} -n 'skel' -- "${@}")

[[ $? != 0 ]] && die 'Try skel -h for more information'

eval set -- "${parsed}"

while true; do
	case "${1}" in
		-t|--template) 
			template="${2}"
			shift 2
		;;
		-r|--replace) 
			word="${2}"
			shift 2
		;;
		-d|--template-directory)
			template_path="${2}"
			shift 2
		;;
		--)
			shift
			break
		;;
		-h|--help) usage 0 ;;
		*) 
			echo 'Internal error.' >&2
			exit 1
		;;
	esac
done

[[ -z "${template:-}" ]] && die "Please specify a template to use."
[[ -n "${@}" ]] && genpath="${@}"
[[ -d "${genpath}" ]] || mkdir --parents "${genpath}"

template_path="${template_path:-${TEMPLATE_SEARCH_PATH}}/${template}" 

[[ -d "${template_path}" ]] || die "Template path ${template_path} not found."

# Create the project directory with specfied templates
cp -r "${template_path}"/* "${genpath}/" || die "Error while copying template files"

# Replace all occurences of word within the project directory
if [[ -n "${word:-}" ]] ; then
	shopt -s globstar
	for file in ${genpath}/** ; do
		[[ -d ${file} ]] && continue
		sed -i -e "s/TEMPLATE/${word}/g" "${file}"
	done
	shopt -u globstar
fi
